<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const userInput = ref('')

// 定义AI模型接口
interface AiModel {
  id: number;
  name: string;        // 显示名称 (displayName)
  modelKey: string;    // 真实的模型标识符 (name)
  icon: string;
  iconClass: string;
  colorClass: string;
  selected: boolean;
  free: boolean;
  // 数据库配置字段
  modelDescription?: string;
  rankPosition?: number;
  flowersCount?: number;
  eggsCount?: number;
  popularityScore?: number;
  discussionsCount?: number;
  responseSpeedScore?: number;
  accuracyScore?: number;
  copywritingScore?: number;
  drawingScore?: number;
  programmingScore?: number;
}

// 定义聊天历史项接口
interface ChatHistoryItem {
  question: string;
  responses: any;
  timestamp: Date;
}

// 定义流式响应接口 - 增加思考过程字段
interface StreamResponse {
  modelKey: string;
  modelName: string;
  content: string;
  thinkingContent: string; // 新增：思考过程内容
  status: 'streaming' | 'success' | 'error';
  error?: string;
  timestamp?: Date;
}

const chatHistory = ref<ChatHistoryItem[]>([])
const currentQuestion = ref('')
const isProcessing = ref(false)
const isChatMode = ref(false)

const aiModels = ref<AiModel[]>([])
const selectedModelsForChat = ref<AiModel[]>([])
const chatInput = ref('')

// 流式响应状态管理
const streamingResponses = ref<{ [key: string]: StreamResponse }>({})
const currentStreamingResponses = ref<{ [key: string]: StreamResponse }>({})

// 添加思考过程展开状态管理
const thinkingExpanded = ref<{ [key: string]: boolean }>({})

// 切换思考过程展开状态
const toggleThinking = (modelKey: string) => {
  thinkingExpanded.value[modelKey] = !thinkingExpanded.value[modelKey]
}

// 检查思考过程是否展开
const isThinkingExpanded = (modelKey: string) => {
  return thinkingExpanded.value[modelKey] || false
}

// 模板引用
const chatTemplate = ref<HTMLElement>()

// 获取AI模型数据
const fetchAiModels = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/ai-models/active`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        // 转换后端数据格式为前端需要的格式，使用数据库中的配置信息
        aiModels.value = result.data.map((model: any) => {
          return {
            id: model.id,
            name: model.displayName,
            modelKey: model.name, // 保存真实的模型标识符
            icon: model.icon,
            iconClass: model.iconClass || 'fas fa-robot',
            colorClass: model.colorClass || 'bg-gray-100 text-gray-600',
            selected: false,
            free: model.isFree,
            // 添加数据库中的配置信息
            modelDescription: model.modelDescription,
            rankPosition: model.rankPosition,
            flowersCount: model.flowersCount,
            eggsCount: model.eggsCount,
            popularityScore: model.popularityScore,
            discussionsCount: model.discussionsCount,
            responseSpeedScore: model.responseSpeedScore,
            accuracyScore: model.accuracyScore,
            copywritingScore: model.copywritingScore,
            drawingScore: model.drawingScore,
            programmingScore: model.programmingScore
          }
        })
        console.log('AI模型数据加载成功:', aiModels.value)
      } else {
        ElMessage.error('获取AI模型失败: ' + result.message)
      }
    } else {
      ElMessage.error('获取AI模型失败')
    }
  } catch (error) {
    console.error('获取AI模型错误:', error)
    ElMessage.error('网络错误，请重试')
    // 如果获取失败，使用HTML文件中的模型数据
    aiModels.value = getDefaultModels()
  }
}

// 获取默认模型数据（备用方案，当API调用失败时使用）
const getDefaultModels = (): AiModel[] => {
  return [
    { id: 1, name: 'Grok-4', modelKey: 'Grok-4', icon: 'G', iconClass: 'fas fa-robot', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: false },
    { id: 2, name: 'AskAgents', modelKey: 'AskAgents', icon: 'A', iconClass: 'fas fa-brain', colorClass: 'bg-purple-100 text-purple-600', selected: false, free: false },
    { id: 3, name: 'DeepSeek-R1', modelKey: 'deepseek-reasoner', icon: 'D', iconClass: 'fas fa-wand-magic-sparkles', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: true },
    { id: 5, name: 'Gemini-2.5-Flash', modelKey: 'Gemini-2.5-Flash', icon: 'G', iconClass: 'fas fa-sparkles', colorClass: 'bg-green-100 text-green-600', selected: false, free: true },
    { id: 6, name: 'DeepSeek-R1联网版', modelKey: 'DeepSeek-R1_Internet', icon: 'D', iconClass: 'fas fa-globe', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: true },
    { id: 7, name: 'GPT-4.1 nano', modelKey: 'GPT-4.1-nano', icon: 'G', iconClass: 'fas fa-microchip', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: true },
    { id: 8, name: '浮点搜索2.0', modelKey: 'Fudian-Searh', icon: '浮', iconClass: 'fas fa-search', colorClass: 'bg-yellow-100 text-yellow-600', selected: false, free: true },
    { id: 9, name: 'Gemini 2.5 Pro优惠版', modelKey: 'Gemini-2.5-Pro-youhui', icon: 'G', iconClass: 'fas fa-gem', colorClass: 'bg-green-100 text-green-600', selected: false, free: false },
    { id: 10, name: 'Gemini 2.5 Pro', modelKey: 'Gemini-2.5-Pro', icon: 'G', iconClass: 'fas fa-gem', colorClass: 'bg-green-100 text-green-600', selected: false, free: false },
    { id: 11, name: 'GPT-4.1', modelKey: 'gpt-4.1', icon: 'G', iconClass: 'fas fa-robot', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: false },
    { id: 12, name: '豆包 1.5 Pro', modelKey: 'doubao-1.5-Pro', icon: '豆', iconClass: 'fas fa-seedling', colorClass: 'bg-red-100 text-red-600', selected: false, free: true },
    { id: 13, name: 'DeepSeek-V3', modelKey: 'deepseek-chat', icon: 'D', iconClass: 'fas fa-wand-magic-sparkles', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: false },
    { id: 14, name: 'Claude-4-Sonnet', modelKey: 'claude-4-sonnet', icon: 'C', iconClass: 'fas fa-user-robot', colorClass: 'bg-purple-100 text-purple-600', selected: false, free: false }
  ]
}


// 根据模型名称获取图标和颜色 - 从数据库配置中获取
const getModelDisplayConfig = (modelName: string) => {
  // 先从当前加载的模型中查找
  const model = aiModels.value.find(m => m.name === modelName || m.modelKey === modelName)
  if (model) {
    return {
      iconClass: model.iconClass || 'fas fa-robot',
      colorClass: model.colorClass || 'bg-gray-100 text-gray-600'
    }
  }
  
  // 如果没找到，使用默认配置
  return { iconClass: 'fas fa-robot', colorClass: 'bg-gray-100 text-gray-600' }
}

// 组件挂载时获取AI模型数据
onMounted(() => {
  fetchAiModels()
})

// 模型选择函数，支持多选
const selectModel = (modelId: number) => {
  const model = aiModels.value.find(m => m.id === modelId)
  if (model) {
    model.selected = !model.selected
  }
}

// 获取选中的AI模型
const getSelectedModels = () => {
  return aiModels.value.filter(model => model.selected)
}

// 更新流式响应的辅助函数 - 确保Vue响应式更新
const updateStreamingResponse = (modelKey: string, updates: Partial<StreamResponse>) => {
  if (currentStreamingResponses.value[modelKey]) {
    // 使用展开运算符创建新对象，确保响应式更新
    currentStreamingResponses.value[modelKey] = {
      ...currentStreamingResponses.value[modelKey],
      ...updates
    }
  } else {
    // 创建新的响应对象
    currentStreamingResponses.value[modelKey] = {
      modelKey,
      modelName: '',
      content: '',
      thinkingContent: '', // 初始化思考过程
      status: 'streaming',
      timestamp: new Date(),
      ...updates
    }
  }
}

// 生成唯一conversationId的函数
const generateConversationId = (userId: string = 'anonymous'): string => {
  const timestamp = Date.now()
  const uuid = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  return `conv-${userId}-${timestamp}-${uuid}`
}

// 获取当前用户ID（这里可以从localStorage、cookie或用户登录状态获取）
const getCurrentUserId = (): string => {
  // 这里可以从用户登录状态、localStorage等获取
  // 暂时使用localStorage，实际项目中应该从用户认证系统获取
  return localStorage.getItem('userId') || 'anonymous'
}

// 处理流式响应 - 支持 THINKING 模式
const handleStreamResponse = async (model: AiModel, question: string, conversationId: string) => {
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
  
  const payload = {
    question: question,
    modelId: model.id,
    conversationId: conversationId, // 传递主conversationId
    history: chatHistory.value,
    contextSize: 5
  }
  
  console.log(`开始流式请求 - 模型: ${model.name}, 主conversationId: ${conversationId}`)
  
  try {
    const response = await fetch(`${baseURL}/chat/ask-stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 初始化流式响应状态
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'streaming',
      timestamp: new Date()
    })
    
    // 处理 Server-Sent Events 流
    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }
    
    const decoder = new TextDecoder()
    let buffer = ''
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        // 流结束，标记为成功
        updateStreamingResponse(model.modelKey, {
          status: 'success',
          timestamp: new Date()
        })
        console.log(`流式响应完成 - 模型: ${model.name}`)
        break
      }
      
      // 解码数据
      buffer += decoder.decode(value, { stream: true })
      
      // 处理完整的SSE事件
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        console.log(`流式响应输出: ${line}`)
        if (line.trim() === '') continue
        
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          
          try {
            // 解析 StreamingOutput JSON
            const streamingOutput = JSON.parse(data)
            console.log('解析的流式输出:', streamingOutput)
            
            if (streamingOutput.type === 'thinking' && streamingOutput.data) {
              // 更新思考过程内容
              const currentThinking = currentStreamingResponses.value[model.modelKey]?.thinkingContent || ''
              updateStreamingResponse(model.modelKey, {
                thinkingContent: currentThinking + streamingOutput.data
              })
              console.log(`思考过程更新 - 模型: ${model.name}`)
            } else if (streamingOutput.type === 'content' && streamingOutput.data) {
              // 更新流式内容
              const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
              updateStreamingResponse(model.modelKey, {
                content: currentContent + streamingOutput.data
              })
            } else if (streamingOutput.type === 'done') {
              // 流结束
              updateStreamingResponse(model.modelKey, {
                status: 'success',
                timestamp: new Date()
              })
              console.log(`流式响应完成 (done) - 模型: ${model.name}`)
              return
            } else if (streamingOutput.type === 'error') {
              // 处理错误
              updateStreamingResponse(model.modelKey, {
                status: 'error',
                error: streamingOutput.data || '未知错误',
                timestamp: new Date()
              })
              console.log(`流式响应错误 - 模型: ${model.name}, 错误: ${streamingOutput.data}`)
              return
            }
          } catch (parseError) {
            console.warn('解析流式输出失败:', parseError, '原始数据:', data)
            // 如果解析失败，按旧格式处理
            const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
            updateStreamingResponse(model.modelKey, {
              content: currentContent + data
            })
          }
        } else if (line.startsWith('event: error')) {
          // 处理错误事件
          updateStreamingResponse(model.modelKey, {
            status: 'error',
            error: '流式响应错误',
            timestamp: new Date()
          })
          console.log(`流式响应错误 - 模型: ${model.name}`)
          return
        }
      }
    }
    
  } catch (error) {
    console.error(`模型 ${model.name} 流式请求失败:`, error)
    
    // 设置错误状态
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'error',
      error: error instanceof Error ? error.message : '网络错误',
      timestamp: new Date()
    })
  }
}

// 创建对话DOM元素的函数 - 使用纯DOM操作，支持可折叠的思考过程
const createChatDOM = (question: string, responses: { [key: string]: StreamResponse }, selectedModels: AiModel[]) => {
  const chatContainer = document.createElement('div')
  chatContainer.className = 'mb-8'
  
  // 创建用户问题DOM
  const questionDiv = document.createElement('div')
  questionDiv.className = 'flex justify-end mb-6'
  questionDiv.innerHTML = `
    <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
      <div class="text-lg font-medium text-gray-800">${question}</div>
    </div>
  `
  
  // 创建AI响应DOM
  const responsesDiv = document.createElement('div')
  responsesDiv.className = 'space-y-8'
  
  // 按照原始选择顺序遍历模型，而不是按照responses的key顺序
  selectedModels.forEach(model => {
    const response = responses[model.modelKey]
    if (!response) return // 如果该模型没有响应，跳过
    
    const modelDiv = document.createElement('div')
    modelDiv.className = 'mb-8'
    
    let statusIcon = ''
    let content = ''
    let thinkingContent = ''
    let statusText = ''
    
    if (response?.status === 'success') {
      statusIcon = '<i class="fas fa-check-circle"></i>'
      content = response.content || '暂无回复内容'
      thinkingContent = response.thinkingContent || ''
      statusText = `回复时间：${formatTimestamp(response.timestamp)}`
    } else if (response?.status === 'error') {
      statusIcon = '<i class="fas fa-exclamation-circle"></i>'
      content = `请求失败: ${response.error || '未知错误'}`
      statusText = `错误时间：${formatTimestamp(response.timestamp)}`
    } else {
      statusIcon = '<i class="fas fa-clock"></i>'
      content = '等待响应中...'
      statusText = '等待中...'
    }
    
    // 获取模型显示配置
    const modelConfig = getModelDisplayConfig(response.modelName || model.modelKey)
    
    // 构建可折叠的思考过程HTML
    const thinkingHtml = thinkingContent ? `
      <div class="mb-4">
        <div class="bg-gray-50 rounded-lg border border-gray-200">
          <div class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors" onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none'; this.querySelector('.fa-chevron-down').classList.toggle('fa-chevron-up'); this.querySelector('.fa-chevron-down').classList.toggle('fa-chevron-down');">
            <div class="flex items-center">
              <span class="text-sm font-medium text-gray-800">思考过程</span>
              <span class="text-xs text-gray-600 ml-2">(${thinkingContent.length} 字符, ${getThinkingDuration(model.modelKey)} 秒)</span>
            </div>
          </div>
          <div class="px-4 pb-4 border-t border-gray-200" style="display: none;">
            <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">${thinkingContent}</div>
          </div>
        </div>
      </div>
    ` : ''
    
    modelDiv.innerHTML = `
      <div class="bg-white rounded-xl pl-0 pt-0 pt-0 pb-5 border-gray-100">
        <div class="flex items-center mb-4">
          <div class="w-8 h-8 rounded-lg flex items-center justify-center mr-3 ${modelConfig.colorClass}">
            <i class="${modelConfig.iconClass} text-sm"></i>
          </div>
          <span class="font-medium text-gray-800">${model.name}</span>
        </div>
        <div class="text-gray-700">
          <div class="prose prose-sm max-w-none">
            ${thinkingHtml}
            <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">${content}</div>
            <div class="text-xs text-gray-400 mt-3">${statusText}</div>
          </div>
        </div>
      </div>
    `
    
    responsesDiv.appendChild(modelDiv)
  })
  
  chatContainer.appendChild(questionDiv)
  chatContainer.appendChild(responsesDiv)
  
  return chatContainer
}

// 进入聊天模式
const enterChatMode = async () => {
  const selectedModels = getSelectedModels()
  if (selectedModels.length === 0) {
    ElMessage.warning('请至少选择一个AI模型')
    return
  }
  
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  selectedModelsForChat.value = selectedModels
  currentQuestion.value = userInput.value
  isChatMode.value = true
  isProcessing.value = true
  
  // 清空当前流式响应
  currentStreamingResponses.value = {}
  
  try {
    // 生成主conversationId
    const userId = getCurrentUserId()
    const conversationId = generateConversationId(userId)
    
    // 更新浏览器地址栏
    const newUrl = `${window.location.pathname}?conversationId=${conversationId}`
    window.history.pushState({ conversationId }, '', newUrl)
    
    console.log('生成主conversationId:', conversationId)
    
    // 并发启动多个流式请求
    const streamPromises = selectedModels.map(model => 
      handleStreamResponse(model, userInput.value, conversationId)
    )
    
    // 等待所有流式请求完成
    await Promise.allSettled(streamPromises)
    
    // 将流式响应保存到聊天历史
    chatHistory.value.push({
      question: userInput.value,
      responses: { ...currentStreamingResponses.value },
      timestamp: new Date()
    })
    
    // 创建对话DOM并添加到历史区域
    const chatDOM = await createChatDOM(userInput.value, currentStreamingResponses.value, selectedModels)
    if (chatDOM) {
      const historyContainer = document.getElementById('history-chat-container')
      if (historyContainer) {
        historyContainer.appendChild(chatDOM)
        
        // 自动滚动到新添加的内容
        setTimeout(() => {
          chatDOM.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'end' 
          })
        }, 100)
      }
    }
    
    // 清空当前流式响应，让当前对话区域消失
    currentStreamingResponses.value = {}
    
    console.log('流式聊天完成 - 聊天历史已更新:', chatHistory.value)
    ElMessage.success('AI回答完成')
    
  } catch (error) {
    console.error('流式聊天错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 返回选择模式 - 保留聊天历史
const backToSelection = () => {
  isChatMode.value = false
  selectedModelsForChat.value = []
  // 注释掉这行，保留聊天历史
  // chatHistory.value = []
  currentQuestion.value = ''
  isProcessing.value = false
  currentStreamingResponses.value = {}
}

// 发送消息
const sendMessage = async () => {
  if (!chatInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  const newQuestion = chatInput.value
  chatInput.value = ''
  currentQuestion.value = newQuestion
  isProcessing.value = true
  
  // 清空当前流式响应
  currentStreamingResponses.value = {}
  
  try {
    const conversationId = route.query.conversationId as string
    if (!conversationId) {
      ElMessage.error('未找到对话ID，请重新进入聊天')
      return
    }
    
    // 并发启动多个流式请求
    const streamPromises = selectedModelsForChat.value.map(model => 
      handleStreamResponse(model, newQuestion, conversationId)
    )
    
    // 等待所有流式请求完成
    await Promise.allSettled(streamPromises)
    
    // 将流式响应保存到聊天历史
    chatHistory.value.push({
      question: newQuestion,
      responses: { ...currentStreamingResponses.value },
      timestamp: new Date()
    })
    
    // 创建对话DOM并添加到历史区域 - 传入selectedModelsForChat确保顺序
    const chatDOM = await createChatDOM(newQuestion, currentStreamingResponses.value, selectedModelsForChat.value)
    if (chatDOM) {
      const historyContainer = document.getElementById('history-chat-container')
      if (historyContainer) {
        historyContainer.appendChild(chatDOM)
        
        // 自动滚动到新添加的内容
        setTimeout(() => {
          chatDOM.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'end' 
          })
        }, 100)
      }
    }
    
    // 清空当前流式响应，让当前对话区域消失
    currentStreamingResponses.value = {}
    
    console.log('继续对话 - 流式聊天完成:', chatHistory.value)
    ElMessage.success('消息发送成功')
    
  } catch (error) {
    console.error('发送消息错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 按钮事件处理
const handleMicrophone = () => {
  ElMessage.info('语音功能开发中...')
}

const handleUpload = () => {
  ElMessage.info('上传功能开发中...')
}

// 获取模型响应数据 - 只从当前流式响应获取
const getModelResponse = (modelKey: string) => {
  return currentStreamingResponses.value[modelKey]
}

// 格式化时间戳
const formatTimestamp = (timestamp: Date | string | undefined) => {
  if (!timestamp) return '未知时间'
  
  try {
    const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp
    return date.toLocaleString().substring(5, 16)
  } catch (error) {
    return '时间格式错误'
  }
}

// 计算思考过程时长（秒数）
const getThinkingDuration = (modelKey: string) => {
  const response = currentStreamingResponses.value[modelKey]
  if (!response || !response.timestamp) return 0
  
  const startTime = new Date(response.timestamp).getTime()
  const endTime = new Date().getTime()
  const duration = Math.floor((endTime - startTime) / 1000)
  
  return Math.max(0, duration)
}

// 根据modelKey获取对应的displayName
const getModelDisplayName = (modelKey: string) => {
  // 先从当前选中的模型中查找
  const selectedModel = selectedModelsForChat.value.find(model => model.modelKey === modelKey)
  if (selectedModel) {
    return selectedModel.name
  }
  
  // 如果没找到，从所有模型中查找
  const allModel = aiModels.value.find(model => model.modelKey === modelKey)
  if (allModel) {
    return allModel.name
  }
  
  // 如果都没找到，返回modelKey本身
  return modelKey
}

// 在script setup中添加模型简介数据
const modelDescriptions = ref<{ [key: string]: string }>({
  'Grok-4': 'Grok-4是xAI开发的最新大语言模型，具有强大的推理能力和广泛的知识覆盖，特别擅长复杂问题分析和创意生成。',
  'AskAgents': 'AskAgents是一个专业的AI代理平台，提供多种专业领域的智能助手，能够处理特定行业的复杂任务。',
  'deepseek-reasoner': 'DeepSeek-R1是深度求索开发的推理模型，具备强大的逻辑推理能力，特别适合需要深度思考的复杂问题。',
  'Gemini-2.5-Flash': 'Gemini-2.5-Flash是Google开发的高效模型，在保持高质量输出的同时具有极快的响应速度，适合实时对话。',
  'DeepSeek-R1_Internet': 'DeepSeek-R1联网版在原有推理能力基础上增加了实时网络搜索功能，能够获取最新信息并进行分析。',
  'GPT-4.1-nano': 'GPT-4.1-nano是OpenAI的轻量级模型，在保持核心能力的同时优化了资源消耗，适合高频使用场景。',
  'Fudian-Searh': '浮点搜索2.0是专业的搜索增强模型，能够进行深度网络搜索和信息整合，提供准确可靠的搜索结果。',
  'Gemini-2.5-Pro-youhui': 'Gemini 2.5 Pro优惠版是Google Pro模型的优惠版本，提供专业级AI能力的同时具有更优惠的价格。',
  'Gemini-2.5-Pro': 'Gemini 2.5 Pro是Google的旗舰模型，具备强大的多模态能力和专业级分析能力，适合复杂任务处理。',
  'gpt-4.1': 'GPT-4.1是OpenAI的最新旗舰模型，在GPT-4基础上进行了全面优化，具备更强的推理能力和更广的知识覆盖。',
  'doubao-1.5-Pro': '豆包 1.5 Pro是字节跳动开发的AI模型，在中文理解和生成方面表现优异，特别适合中文场景应用。',
  'deepseek-chat': 'DeepSeek-V3是深度求索的通用对话模型，在保持高效性能的同时提供流畅的对话体验。',
  'claude-4-sonnet': 'Claude-4-Sonnet是Anthropic开发的高性能模型，以安全性和可靠性著称，特别适合需要谨慎处理的敏感任务。'
})

// 获取模型简介 - 从数据库配置中获取
const getModelDescription = (modelKey: string) => {
  const model = aiModels.value.find(m => m.modelKey === modelKey)
  if (model && model.modelDescription) {
    return model.modelDescription
  }
  
  // 如果数据库中没有，使用硬编码的备用描述
  return modelDescriptions.value[modelKey] || '暂无模型简介'
}

// 点击查看模型详情
const viewModelDetails = (modelKey: string) => {
  ElMessage.info(`查看 ${getModelDisplayName(modelKey)} 的详细模型信息`)
  // 这里可以添加跳转到详情页面的逻辑
}

// 在script setup中添加模型详细信息数据
const modelDetails = ref<{ [key: string]: any }>({
  'Grok-4': {
    rank: 15,
    flowers: 8,
    eggs: 2,
    popularity: 12543,
    discussions: 12,
    ratings: {
      responseSpeed: { score: 4.2, stars: 4 },
      accuracy: { score: 4.5, stars: 4 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.3, stars: 4 }
    }
  },
  'AskAgents': {
    rank: 28,
    flowers: 5,
    eggs: 1,
    popularity: 8921,
    discussions: 8,
    ratings: {
      responseSpeed: { score: 3.8, stars: 4 },
      accuracy: { score: 4.2, stars: 4 },
      copywriting: { score: 3.6, stars: 4 },
      drawing: { score: 2.8, stars: 3 },
      programming: { score: 4.0, stars: 4 }
    }
  },
  'deepseek-reasoner': {
    rank: 12,
    flowers: 15,
    eggs: 3,
    popularity: 18765,
    discussions: 25,
    ratings: {
      responseSpeed: { score: 3.5, stars: 3 },
      accuracy: { score: 4.8, stars: 5 },
      copywriting: { score: 4.2, stars: 4 },
      drawing: { score: 2.5, stars: 2 },
      programming: { score: 4.6, stars: 5 }
    }
  },
  'Gemini-2.5-Flash': {
    rank: 8,
    flowers: 22,
    eggs: 4,
    popularity: 23456,
    discussions: 18,
    ratings: {
      responseSpeed: { score: 4.8, stars: 5 },
      accuracy: { score: 4.3, stars: 4 },
      copywriting: { score: 4.1, stars: 4 },
      drawing: { score: 3.9, stars: 4 },
      programming: { score: 4.0, stars: 4 }
    }
  },
  'DeepSeek-R1_Internet': {
    rank: 18,
    flowers: 12,
    eggs: 2,
    popularity: 15678,
    discussions: 15,
    ratings: {
      responseSpeed: { score: 3.8, stars: 4 },
      accuracy: { score: 4.6, stars: 5 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 2.8, stars: 3 },
      programming: { score: 4.4, stars: 4 }
    }
  },
  'GPT-4.1-nano': {
    rank: 25,
    flowers: 6,
    eggs: 1,
    popularity: 9876,
    discussions: 9,
    ratings: {
      responseSpeed: { score: 4.5, stars: 4 },
      accuracy: { score: 4.0, stars: 4 },
      copywriting: { score: 3.8, stars: 4 },
      drawing: { score: 3.2, stars: 3 },
      programming: { score: 3.9, stars: 4 }
    }
  },
  'Fudian-Searh': {
    rank: 35,
    flowers: 4,
    eggs: 3,
    popularity: 6543,
    discussions: 6,
    ratings: {
      responseSpeed: { score: 3.2, stars: 3 },
      accuracy: { score: 3.8, stars: 4 },
      copywriting: { score: 3.4, stars: 3 },
      drawing: { score: 2.0, stars: 2 },
      programming: { score: 3.6, stars: 4 }
    }
  },
  'Gemini-2.5-Pro-youhui': {
    rank: 20,
    flowers: 18,
    eggs: 2,
    popularity: 14567,
    discussions: 14,
    ratings: {
      responseSpeed: { score: 4.0, stars: 4 },
      accuracy: { score: 4.4, stars: 4 },
      copywriting: { score: 4.2, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.1, stars: 4 }
    }
  },
  'Gemini-2.5-Pro': {
    rank: 6,
    flowers: 35,
    eggs: 5,
    popularity: 28765,
    discussions: 32,
    ratings: {
      responseSpeed: { score: 4.2, stars: 4 },
      accuracy: { score: 4.7, stars: 5 },
      copywriting: { score: 4.5, stars: 4 },
      drawing: { score: 4.3, stars: 4 },
      programming: { score: 4.4, stars: 4 }
    }
  },
  'gpt-4.1': {
    rank: 3,
    flowers: 45,
    eggs: 8,
    popularity: 35678,
    discussions: 42,
    ratings: {
      responseSpeed: { score: 4.0, stars: 4 },
      accuracy: { score: 4.8, stars: 5 },
      copywriting: { score: 4.6, stars: 5 },
      drawing: { score: 4.1, stars: 4 },
      programming: { score: 4.7, stars: 5 }
    }
  },
  'doubao-1.5-Pro': {
    rank: 22,
    flowers: 9,
    eggs: 2,
    popularity: 12345,
    discussions: 11,
    ratings: {
      responseSpeed: { score: 4.1, stars: 4 },
      accuracy: { score: 4.2, stars: 4 },
      copywriting: { score: 4.3, stars: 4 },
      drawing: { score: 3.5, stars: 4 },
      programming: { score: 3.8, stars: 4 }
    }
  },
  'deepseek-chat': {
    rank: 16,
    flowers: 11,
    eggs: 3,
    popularity: 13456,
    discussions: 13,
    ratings: {
      responseSpeed: { score: 4.3, stars: 4 },
      accuracy: { score: 4.4, stars: 4 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 3.0, stars: 3 },
      programming: { score: 4.2, stars: 4 }
    }
  },
  'claude-4-sonnet': {
    rank: 9,
    flowers: 28,
    eggs: 4,
    popularity: 19876,
    discussions: 21,
    ratings: {
      responseSpeed: { score: 3.9, stars: 4 },
      accuracy: { score: 4.6, stars: 5 },
      copywriting: { score: 4.4, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.3, stars: 4 }
    }
  }
})

// 获取模型详细信息 - 从数据库配置中获取
const getModelDetails = (modelKey: string) => {
  const model = aiModels.value.find(m => m.modelKey === modelKey)
  if (model) {
    return {
      rank: model.rankPosition || 0,
      flowers: model.flowersCount || 0,
      eggs: model.eggsCount || 0,
      popularity: model.popularityScore || 0,
      discussions: model.discussionsCount || 0,
      ratings: {
        responseSpeed: { score: model.responseSpeedScore || 0, stars: Math.round(model.responseSpeedScore || 0) },
        accuracy: { score: model.accuracyScore || 0, stars: Math.round(model.accuracyScore || 0) },
        copywriting: { score: model.copywritingScore || 0, stars: Math.round(model.copywritingScore || 0) },
        drawing: { score: model.drawingScore || 0, stars: Math.round(model.drawingScore || 0) },
        programming: { score: model.programmingScore || 0, stars: Math.round(model.programmingScore || 0) }
      }
    }
  }
  
  // 如果数据库中没有，使用硬编码的备用数据
  return modelDetails.value[modelKey] || {
    rank: 50,
    flowers: 0,
    eggs: 0,
    popularity: 1000,
    discussions: 0,
    ratings: {
      responseSpeed: { score: 3.0, stars: 3 },
      accuracy: { score: 3.0, stars: 3 },
      copywriting: { score: 3.0, stars: 3 },
      drawing: { score: 3.0, stars: 3 },
      programming: { score: 3.0, stars: 3 }
    }
  }
}

// 生成星级评分HTML
const generateStarRating = (score: number, maxStars: number = 5) => {
  const fullStars = Math.floor(score)
  const hasHalfStar = score % 1 >= 0.5
  const emptyStars = maxStars - fullStars - (hasHalfStar ? 1 : 0)
  
  let starsHtml = ''
  
  // 满星
  for (let i = 0; i < fullStars; i++) {
    starsHtml += '<i class="fas fa-star text-orange-400"></i>'
  }
  
  // 半星
  if (hasHalfStar) {
    starsHtml += '<i class="fas fa-star-half-alt text-orange-400"></i>'
  }
  
  // 空星
  for (let i = 0; i < emptyStars; i++) {
    starsHtml += '<i class="far fa-star text-gray-300"></i>'
  }
  
  return starsHtml
}

// 添加悬停状态管理
const hoveredModelId = ref<number | null>(null)
const hoverTimeout = ref<NodeJS.Timeout | null>(null)

// 鼠标进入模型卡片
const handleMouseEnter = (modelId: number) => {
  // 清除任何待执行的隐藏定时器
  if (hoverTimeout.value) {
    clearTimeout(hoverTimeout.value)
    hoverTimeout.value = null
  }
  hoveredModelId.value = modelId
}

// 鼠标离开模型卡片
const handleMouseLeave = (modelId: number) => {
  // 延迟隐藏，给用户时间移动到弹出框
  hoverTimeout.value = setTimeout(() => {
    hoveredModelId.value = null
  }, 200) // 增加延迟时间到200ms
}

// 鼠标进入弹出框
const handlePopupMouseEnter = () => {
  // 清除隐藏定时器，保持弹出框显示
  if (hoverTimeout.value) {
    clearTimeout(hoverTimeout.value)
    hoverTimeout.value = null
  }
}

// 鼠标离开弹出框
const handlePopupMouseLeave = () => {
  // 立即隐藏弹出框
  hoveredModelId.value = null
}

// 检查模型是否悬停
const isModelHovered = (modelId: number) => {
  return hoveredModelId.value === modelId
}

// 历史记录相关状态
const showHistoryDialog = ref(false)
const historyLoading = ref(false)
const conversationHistory = ref<ConversationHistoryItem[]>([])

// 定义历史记录项接口
interface ConversationHistoryItem {
  conversationId: string
  question: string
  timestamp: Date
  modelCount: number
  models: string[]
}

// 计算属性：按时间分组的历史记录
const groupedHistory = computed(() => {
  const today = new Date()
  const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const sevenDaysAgo = new Date(todayStart.getTime() - 7 * 24 * 60 * 60 * 1000)
  const thirtyDaysAgo = new Date(todayStart.getTime() - 30 * 24 * 60 * 60 * 1000)
  
  const todayRecords: ConversationHistoryItem[] = []
  const recentRecords: ConversationHistoryItem[] = []
  const olderRecords: ConversationHistoryItem[] = []
  
  conversationHistory.value.forEach(item => {
    const itemDate = new Date(item.timestamp)
    
    if (itemDate >= todayStart) {
      todayRecords.push(item)
    } else if (itemDate >= sevenDaysAgo) {
      recentRecords.push(item)
    } else if (itemDate >= thirtyDaysAgo) {
      olderRecords.push(item)
    }
  })
  
  return {
    today: todayRecords,
    recent: recentRecords,
    older: olderRecords
  }
})

// 格式化时间显示
const formatHistoryTime = (timestamp: Date) => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return timestamp.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 获取历史记录数据
const fetchConversationHistory = async () => {
  try {
    historyLoading.value = true
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const userId = getCurrentUserId()
    
    const response = await fetch(`${baseURL}/chat/history?userId=${userId}`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        conversationHistory.value = result.data.map((item: any) => ({
          conversationId: item.conversationId,
          question: item.question,
          timestamp: new Date(item.timestamp),
          modelCount: item.modelCount || 0,
          models: item.models || []
        }))
        console.log('历史记录加载成功:', conversationHistory.value)
      } else {
        ElMessage.error('获取历史记录失败: ' + result.message)
      }
    } else {
      ElMessage.error('获取历史记录失败')
    }
  } catch (error) {
    console.error('获取历史记录错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    historyLoading.value = false
  }
}

// 显示历史记录对话框
const showHistory = async () => {
  showHistoryDialog.value = true
  await fetchConversationHistory()
}

// 关闭历史记录对话框
const closeHistoryDialog = () => {
  showHistoryDialog.value = false
}

// 清空账号历史
const clearAccountHistory = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const userId = getCurrentUserId()
    
    const response = await fetch(`${baseURL}/chat/history/clear?userId=${userId}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      conversationHistory.value = []
      ElMessage.success('历史记录已清空')
    } else {
      ElMessage.error('清空失败')
    }
  } catch (error) {
    console.error('清空历史记录失败:', error)
    ElMessage.error('清空失败')
  }
}

// 点击历史记录项
const selectHistoryItem = (conversationId: string) => {
  // 跳转到独立的聊天页面
  router.push(`/chat/${conversationId}`)
}

// 加载对话详细信息
const loadConversationDetails = async (conversationId: string) => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/conversation/${conversationId}`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        // 加载对话历史到chatHistory
        chatHistory.value = result.data.messages || []
        
        // 设置选中的模型
        if (result.data.models) {
          selectedModelsForChat.value = result.data.models.map((modelInfo: any) => {
            const model = aiModels.value.find(m => m.id === modelInfo.id)
            return model || {
              id: modelInfo.id,
              name: modelInfo.name,
              modelKey: modelInfo.modelKey,
              iconClass: 'fas fa-robot',
              colorClass: 'bg-gray-100 text-gray-600',
              selected: false,
              free: false
            }
          })
        }
        
        console.log('对话详情加载成功:', result.data)
      }
    }
  } catch (error) {
    console.error('加载对话详情失败:', error)
    ElMessage.error('加载对话详情失败')
  }
}

// 删除历史记录 - 添加确认框
const deleteHistoryItem = async (conversationId: string) => {
  try {
    // 使用 ElMessageBox 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这条历史记录吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/history/${conversationId}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      // 从本地列表中移除
      conversationHistory.value = conversationHistory.value.filter(
        item => item.conversationId !== conversationId
      )
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不显示错误信息
      return
    }
    console.error('删除历史记录失败:', error)
    ElMessage.error('删除失败')
  }
}
</script>

<template>
  <div class="bg-white h-screen overflow-hidden">
    <!-- 整体布局：左侧导航 + 右侧内容 -->
    <div class="flex">
      <!-- 左侧固定导航栏 -->
      <div class="w-[119px] bg-white flex flex-col sticky top-0 h-screen">
        <div class="p-6 text-center">
          <div class="font-['Pacifico'] text-2xl text-primary tracking-wider">AI Chat</div>
        </div>
        <div class="px-4 py-4 flex flex-col items-center text-center">
          <div class="w-16 h-16 bg-gradient-to-r from-primary to-secondary rounded-full flex items-center justify-center text-white shadow-lg mb-3">
            <span class="text-2xl font-semibold">M</span>
          </div>
          <div class="text-base font-medium tracking-wide">默默</div>
          <div class="text-sm text-gray-600 flex items-center mt-1">
            <i class="fas fa-crown text-yellow-400 mr-1"></i>
            <span class="font-medium">VIP会员</span>
          </div>
        </div>
        <nav class="flex-1 px-3 py-6">
          <div class="space-y-2">
            <a 
              @click="showHistory" 
              class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors cursor-pointer"
            >
              <i class="fas fa-history w-5 h-5 text-primary mb-1"></i>
              <span class="font-medium text-sm tracking-wide">历史记录</span>
            </a>
            <a href="#" class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors">
              <i class="fas fa-star w-5 h-5 mb-1"></i>
              <span class="font-medium text-sm tracking-wide">收藏夹</span>
            </a>
            <a href="#" class="flex flex-col items-center px-4 py-3 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors">
              <i class="fas fa-cog w-5 h-5 mb-1"></i>
              <span class="font-medium text-sm tracking-wide">设置</span>
            </a>
          </div>
        </nav>
      </div>

      <!-- 历史记录侧边栏 - 紧靠浏览器左侧 -->
      <div 
        v-if="showHistoryDialog" 
        class="fixed left-0 top-0 h-full w-80 bg-white shadow-2xl z-50 flex flex-col border-r border-gray-200"
      >
        <!-- 对话框头部 - 去掉边框 -->
        <div class="flex items-center justify-between p-4 bg-gray-50">
          <h3 class="text-lg font-semibold text-gray-800">历史记录</h3>
          <div class="flex items-center space-x-2">
            <button 
              @click="clearAccountHistory"
              class="px-3 py-1 text-sm text-gray-600 bg-gray-200 rounded-md hover:bg-gray-300 transition-colors"
            >
              清空账号历史
            </button>
            <button 
              @click="closeHistoryDialog"
              class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors"
            >
              ✕
            </button>
          </div>
        </div>
        
        <!-- 对话框内容 -->
        <div class="flex-1 overflow-y-auto">
          <div v-if="historyLoading" class="flex items-center justify-center py-8">
            <i class="fas fa-spinner fa-spin text-2xl text-primary mr-3"></i>
            <span class="text-gray-600">加载中...</span>
          </div>
          
          <div v-else-if="conversationHistory.length === 0" class="text-center py-8 px-4">
            <i class="fas fa-history text-4xl text-gray-300 mb-4"></i>
            <p class="text-gray-500">暂无历史记录</p>
          </div>
          
          <div v-else class="p-4 space-y-6">
            <!-- 今天 -->
            <div v-if="groupedHistory.today.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-day mr-2"></i>
                今天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.today" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 近7天 -->
            <div v-if="groupedHistory.recent.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-week mr-2"></i>
                近7天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.recent" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 近30天 -->
            <div v-if="groupedHistory.older.length > 0">
              <h4 class="text-sm font-semibold text-gray-600 mb-3 flex items-center">
                <i class="fas fa-calendar-alt mr-2"></i>
                近30天
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="item in groupedHistory.older" 
                  :key="item.conversationId"
                  @click="selectHistoryItem(item.conversationId)"
                  class="p-3 rounded-lg bg-gray-50 hover:bg-blue-50 hover:border-blue-200 cursor-pointer transition-all group border border-transparent"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-800 line-clamp-2 group-hover:text-blue-600 transition-colors">
                        {{ item.question }}
                      </p>
                      <div class="flex items-center mt-2 text-xs text-gray-500">
                        <span>{{ formatHistoryTime(item.timestamp) }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ item.modelCount }}个模型</span>
                      </div>
                    </div>
                    <div class="flex items-center space-x-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="deleteHistoryItem(item.conversationId)"
                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-400 hover:bg-red-100 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <i class="fas fa-trash text-xs"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史对话区：只在聊天模式显示 -->
      <div v-if="isChatMode" class="w-60 bg-white flex flex-col sticky top-0 h-screen">
        <div class="p-4">
          <div class="font-medium text-base mb-4">当前对话目录</div>
          <div class="space-y-4 overflow-y-auto flex-1">
            <div 
              v-for="(item, index) in chatHistory" 
              :key="index"
              class="bg-gray-50 rounded-lg p-3 cursor-pointer hover:bg-gray-100"
            >
              <!-- 问题显示 -->
              <div class="text-sm font-medium mb-3 text-gray-800">{{ item.question.substring(0, 15) }}...</div>
              
              <!-- 模型回答列表 -->
              <div class="space-y-2">
                <div 
                  v-for="(response, modelName) in item.responses" 
                  :key="modelName"
                  class="bg-white rounded-lg p-2"
                >
                  <div class="flex items-center mb-1">
                    <!-- 模型图标 -->
                    <div :class="['w-4 h-4 rounded flex items-center justify-center mr-2', getModelDisplayConfig(String(modelName)).colorClass]">
                      <i :class="[getModelDisplayConfig(String(modelName)).iconClass, 'text-xs']"></i>
                    </div>
                    <!-- 模型名称：修改这里 -->
                    <span class="text-xs font-medium text-gray-700">{{ getModelDisplayName(String(modelName)) }}的回答</span>
                  </div>
                  <!-- 回答内容预览 -->
                  <div class="text-xs text-gray-500 line-clamp-2">
                    {{ typeof response === 'string' ? response.substring(0, 30) + '...' : (response?.content || 'AI回复').substring(0, 30) + '...' }}
                  </div>
                </div>
              </div>
              
              <!-- 时间戳 -->
              <div class="text-xs text-gray-400 mt-2">{{ item.timestamp.toLocaleString().substring(0, 16) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主内容区：统一的自然流动布局 -->
      <div class="flex-1 h-screen overflow-y-auto pr-4">
        <div class="max-w-4xl mx-auto p-6" :class="{'min-h-screen flex flex-col': !isChatMode}">
          
          <!-- 首页模式：AI模型选择 -->
          <div v-if="!isChatMode" class="flex-1 flex flex-col">
            <!-- 顶部导航 -->
            <div class="h-16 flex items-center justify-center px-8 bg-gradient-to-r from-white via-gray-50 to-white rounded-xl shadow-sm border border-gray-100 mb-6">
              <nav class="flex items-center space-x-10">
                <a href="#" class="text-primary font-medium relative group">
                  <span class="relative z-10">最新推荐</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"></span>
                </a>
                <a href="#" class="text-gray-600 hover:text-gray-900 font-medium relative group">
                  <span class="relative z-10">Agents</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"></span>
                </a>
                <a href="#" class="text-gray-600 hover:text-gray-900 font-medium relative group">
                  <span class="relative z-10">联网搜索组</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"></span>
                </a>
                <a href="#" class="text-gray-600 hover:text-gray-900 font-medium relative group">
                  <span class="relative z-10">写作组</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"></span>
                </a>
                <a href="#" class="text-gray-600 hover:text-gray-900 font-medium relative group">
                  <span class="relative z-10">编程组</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"></span>
                </a>
                <a href="#" class="text-gray-600 hover:text-gray-900 font-medium relative group">
                  <span class="relative z-10">绘画组</span>
                  <span class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"></span>
                </a>
              </nav>
            </div>

            <!-- AI模型卡片网格 -->
            <div class="grid grid-cols-4 gap-4 mb-8">
              <div
                v-for="model in aiModels"
                :key="model.id"
                @click="selectModel(model.id)"
                @mouseenter="handleMouseEnter(model.id)"
                @mouseleave="handleMouseLeave(model.id)"
                :class="[
                  'bg-white p-2.5 rounded-lg border cursor-pointer transition-all relative',
                  model.selected ? 'border-primary shadow-md' : 'border-gray-200 hover:border-primary/30 hover:shadow-md'
                ]"
              >
                <div class="flex items-start space-x-2">
                  <div :class="['w-6 h-6 rounded-lg flex items-center justify-center flex-shrink-0', model.colorClass]">
                    <i :class="[model.iconClass, 'text-sm']"></i>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="font-medium text-sm">{{ model.name }}</div>
                    <div v-if="model.selected" class="text-xs text-primary mt-1">已选择</div>
                  </div>
                </div>
                
                <!-- 详细模型信息弹出框 -->
                <div 
                  v-if="isModelHovered(model.id)"
                  @mouseenter="handlePopupMouseEnter"
                  @mouseleave="handlePopupMouseLeave"
                  @click.stop
                  class="absolute top-full left-0 mt-2 w-80 bg-white rounded-lg shadow-xl border border-gray-200 z-50"
                >
                  <!-- 弹出框内容 -->
                  <div class="p-4">
                    <!-- 头部信息 -->
                    <div class="flex items-center mb-3">
                      <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                        <i :class="[model.iconClass, 'text-sm']"></i>
                      </div>
                      <div>
                        <div class="font-semibold text-lg text-gray-800">{{ model.name }}</div>
                      </div>
                    </div>
                    
                    <!-- 模型简介 -->
                    <div class="mb-4">
                      <div class="flex items-center justify-between mb-3">
                        <span class="font-medium text-gray-800">模型简介</span>
                        <button 
                          @click.stop="viewModelDetails(model.modelKey)"
                          class="text-blue-500 text-sm hover:text-blue-600 hover:underline"
                        >
                          查看详情 >
                        </button>
                      </div>
                      
                      <div class="text-sm text-gray-600 leading-relaxed">
                        {{ getModelDescription(model.modelKey) }}
                      </div>
                    </div>
                    
                    <!-- 用户口碑 -->
                    <div class="mb-4">
                      <div class="mb-3">
                        <span class="font-medium text-gray-800">用户口碑</span>
                      </div>
                      
                      <!-- 能力评分 -->
                      <div class="space-y-2">
                        <div class="flex items-center justify-between">
                          <span class="text-sm text-gray-600">响应速度</span>
                          <div class="flex items-center">
                            <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.responseSpeed.score)"></div>
                            <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.responseSpeed.score }}分</span>
                          </div>
                        </div>
                        
                        <div class="flex items-center justify-between">
                          <span class="text-sm text-gray-600">回答准确度</span>
                          <div class="flex items-center">
                            <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.accuracy.score)"></div>
                            <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.accuracy.score }}分</span>
                          </div>
                        </div>
                        
                        <div class="flex items-center justify-between">
                          <span class="text-sm text-gray-600">文案能力</span>
                          <div class="flex items-center">
                            <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.copywriting.score)"></div>
                            <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.copywriting.score }}分</span>
                          </div>
                        </div>
                        
                        <div class="flex items-center justify-between">
                          <span class="text-sm text-gray-600">绘画能力</span>
                          <div class="flex items-center">
                            <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.drawing.score)"></div>
                            <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.drawing.score }}分</span>
                          </div>
                        </div>
                        
                        <div class="flex items-center justify-between">
                          <span class="text-sm text-gray-600">编程能力</span>
                          <div class="flex items-center">
                            <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.programming.score)"></div>
                            <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.programming.score }}分</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 底部输入区域 -->
            <div class="mt-auto bg-white rounded-2xl border border-gray-200 p-6">
              <div class="relative">
                <textarea 
                  v-model="userInput"
                  class="w-full border-none bg-gray-50/70 rounded-2xl pl-6 pr-32 py-5 resize-none focus:ring-2 focus:ring-primary focus:outline-none text-base" 
                  rows="3" 
                  placeholder="请输入问题（提示：输入后可快速生成AI回答，支持截图粘贴、图片/文件上传）"
                ></textarea>
                <div class="absolute right-4 bottom-4 flex items-center space-x-2">
                  <button @click="handleMicrophone" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                    <i class="fas fa-microphone"></i>
                  </button>
                  <button @click="handleUpload" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                    <i class="fas fa-paperclip"></i>
                  </button>
                  <button @click="enterChatMode" class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90">
                    <i class="fas fa-paper-plane"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 聊天模式：内部滚动容器 -->
          <div v-else class="pb-40">
            <!-- 聊天内容滚动区域 -->
            <div class="flex-1 overflow-y-auto pr-2">
              <!-- 历史对话区域：静态容器，通过JavaScript动态添加DOM -->
              <div id="history-chat-container">
                <!-- 历史对话会通过JavaScript动态添加到这里 -->
              </div>

              <!-- 当前对话区域：Vue模板，用于流式更新 -->
              <div v-if="isProcessing || Object.keys(currentStreamingResponses).length > 0" class="mb-8">
                <!-- 当前用户问题 -->
                <div class="flex justify-end mb-6">
                  <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
                    <div class="text-lg font-medium text-gray-800">{{ currentQuestion }}</div>
                  </div>
                </div>

                <!-- 当前AI模型响应 -->
                <div 
                  v-for="model in selectedModelsForChat" 
                  :key="`current-${model.id}`"
                  class="mb-8"
                >
                  <div class="bg-white rounded-xl pl-0 pt-0 pt-0 pb-5 border-gray-100">
                    <div class="flex items-center mb-4">
                      <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                        <i :class="[model.iconClass, 'text-sm']"></i>
                      </div>
                      <span class="font-medium text-gray-800">{{ model.name }}</span>
                    </div>
                    <div>
                      <div v-if="isProcessing && !getModelResponse(model.modelKey)" class="flex items-center text-gray-500">
                        <i class="fas fa-spinner fa-spin mr-2"></i>
                        <span>AI正在思考中...</span>
                      </div>
                      <div v-else class="text-gray-700">
                        <!-- 可折叠的思考过程显示 -->
                        <div v-if="getModelResponse(model.modelKey)?.thinkingContent" class="mb-4">
                          <div class="bg-gray-50 rounded-lg border border-gray-200">
                            <!-- 思考过程标题栏（可点击） -->
                            <div 
                              @click="toggleThinking(model.modelKey)"
                              class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                            >
                              <div class="flex items-center">
                                <span class="text-sm font-medium text-gray-800">思考过程</span>
                                <span class="text-xs text-gray-600 ml-2">
                                  ({{ getModelResponse(model.modelKey)?.thinkingContent?.length || 0 }} 字符, {{ getThinkingDuration(model.modelKey) }} 秒)
                                </span>
                              </div>
                            </div>
                            
                            <!-- 思考过程内容（可折叠） -->
                            <div 
                              v-show="isThinkingExpanded(model.modelKey)"
                              class="px-4 pb-4 border-t border-gray-200"
                            >
                              <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">
                                {{ getModelResponse(model.modelKey)?.thinkingContent }}
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        <!-- 流式响应内容 -->
                        <div v-if="getModelResponse(model.modelKey)?.status === 'streaming'" class="prose prose-sm max-w-none">
                          <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                            {{ getModelResponse(model.modelKey)?.content || '正在生成回答...' }}
                          </div>
                          <div class="text-xs text-gray-400 mt-3">
                            正在流式输出中...
                          </div>
                        </div>
                        <!-- 成功响应 -->
                        <div v-else-if="getModelResponse(model.modelKey)?.status === 'success'" class="prose prose-sm max-w-none">
                          <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                            {{ getModelResponse(model.modelKey)?.content || '暂无回复内容' }}
                          </div>
                          <div class="text-xs text-gray-400 mt-3">
                            回复时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                          </div>
                        </div>
                        <!-- 错误响应 -->
                        <div v-else-if="getModelResponse(model.modelKey)?.status === 'error'" class="text-red-600">
                          <div class="flex items-start">
                            <i class="fas fa-exclamation-triangle mr-2 mt-1 flex-shrink-0"></i>
                            <div>
                              <div class="font-medium mb-1">请求失败</div>
                              <div class="text-sm text-red-500">{{ getModelResponse(model.modelKey)?.error || '未知错误' }}</div>
                              <div class="text-xs text-gray-400 mt-2">
                                错误时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                              </div>
                            </div>
                          </div>
                        </div>
                        <!-- 无响应数据 -->
                        <div v-else class="text-gray-500 italic">
                          <i class="fas fa-clock mr-2"></i>
                          等待响应中...
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 聊天模式的固定底部输入框 -->
    <div v-if="isChatMode" class="fixed bottom-0 left-[119px] right-0 bg-transparent z-50" :style="{'left': isChatMode ? '320px' : '119px'}">
      <div class="max-w-4xl mx-auto pl-6 pr-6 pt-6 pb-0">
        <div class="bg-white rounded-1xl  border-gray-200  pt-0 pb-6">
          <!-- 顶部返回按钮 -->
          <div class="flex justify-end mb-0 mr-3 p-3">
              <button @click="backToSelection" class="text-primary hover:text-primary/80 font-medium text-sm flex items-center">
                <i class="fas fa-arrow-left mr-2"></i>
                返回选择
              </button>
            </div>
          <div class="bg-white rounded-2xl border border-gray-200 p-6">
            <div class="relative">
              <textarea 
                v-model="chatInput"
                class="w-full border-none bg-gray-50/70 rounded-2xl pl-6 pr-32 py-5 resize-none focus:ring-2 focus:ring-primary focus:outline-none text-base" 
                rows="3" 
                placeholder="继续对话..."
              ></textarea>
              <div class="absolute right-4 bottom-4 flex items-center space-x-2">
                <button @click="handleMicrophone" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-microphone"></i>
                </button>
                <button @click="handleUpload" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-paperclip"></i>
                </button>
                <button @click="sendMessage" class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90">
                  <i class="fas fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 确保页面内容可以超出视窗，触发滚动条 */
:global(html) {
  overflow-y: auto;
}

:global(body) {
  overflow-y: auto;
  margin: 0;
  padding: 0;
}

/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 工具提示样式优化 */
.group:hover .group-hover\:opacity-100 {
  opacity: 1;
}

/* 星级评分样式 */
.fa-star, .fa-star-half-alt {
  font-size: 12px;
  margin-right: 2px;
}

/* 确保 TailwindCSS 样式优先级 */
</style>